package com.xfpp.javaDemo.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map; 

/**
 *
 * Http工具类
 *
 */

public class HttpUtil {
	private static String url = "http://www.paihe.cn/OpenAPI/Hishop.Open.Api.";
	private static final String appKey = "open243630yhd9xyz";
	private static final String appSecreate = "oas630yhd9xyz3zu9g4hl";
	
	private static Map<String,Object> params = new HashMap<String,Object>();
	
	/**
	 * 交易API
	 * @param args
	 */
	private static final String tradeRoot= "ITrade."; //交易根路径
	private static final String getSoldTrades= "GetSoldTrades/";  //获取当前商家的订单列表（根据创建时间）
	private static final String getIncrementSoldTrades= "GetIncrementSoldTrades/"; //查询订单的增量交易数据（根据修改时间） 
	private static final String getTrade= "GetTrade/"; //获取单笔交易的详细信息
	private static final String sendLogistic= "SendLogistic/"; //订单发货
	private static final String updateTradeMemo= "UpdateTradeMemo/"; //修改交易备注
	private static final String changLogistics= "ChangLogistics/"; //更新物流信息
	
	
	/**
	 * 商品API
	 * @param args
	 */
	private static final String goodRoot= "IProduct."; //商品根路径
	private static final String getSoldProducts= "GetSoldProducts/";  //获取当前商家的商品列表
	private static final String getProduct= "GetProduct/"; //获取指定商品的详情信息
	private static final String updateProductQuantity= "UpdateProductQuantity/"; //商品/SKU库存修改(提供按照全量或增量形式修改宝贝/SKU库存的功能)
	private static final String updateProductApproveStatus= "UpdateProductApproveStatus/"; //修改商品销售状态 (上架， 下架， 入库)
	
	/**
	 * 会员API
	 * @param args
	 */
	private static final String userRoot= "IUser."; //会员根路径
	private static final String getUsers= "GetUsers/";  //获取用户列表，根据时间段获取这段时间内注册的用户
	private static final String getUser= "GetUser/"; //获取用户信息，根据会员名获取单个用户详细信息
	private static final String addUser= "AddUser/"; //添加用户
	
	static {
		params.put("app_key", appKey);
		params.put("timestamp", "2016-08-22 16:03:50");
		params.put("sign", "81007DC334166F8E22F50A0227EE9B5A");
	}
	
	
	//DEMO
	public static void main(String[] args) {
		
		url += tradeRoot + sendLogistic;
		
		//参数设置
		
		params.put("company_name", "韵达快递");
		params.put("out_sid", "1000712888014");
		params.put("tid", "2016082272351960");
		
		System.out.println(sendPost(url,params));
	}
	

	 /**
     * 向指定 URL 发送POST方法的请求     
     * @param url 发送请求的 URL    
     * @param params 请求的参数集合     
     * @return 远程资源的响应结果
     */
	@SuppressWarnings("unused")
	public static String sendPost(String url, Map<String, Object> params) {
        OutputStreamWriter out = null;
        BufferedReader in = null;        
        StringBuilder result = new StringBuilder(); 
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn =(HttpURLConnection) realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // POST方法
            conn.setRequestMethod("POST");
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.connect();
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            // 发送请求参数            
            if (params != null) {
		          StringBuilder param = new StringBuilder(); 
		          for (Map.Entry<String, Object> entry : params.entrySet()) {
		        	  if(param.length()>0){
		        		  param.append("&");
		        	  }	        	  
		        	  param.append(entry.getKey());
		        	  param.append("=");
		        	  param.append(entry.getValue());		        	  
		        	  //System.out.println(entry.getKey()+":"+entry.getValue());
		          }
		          //System.out.println("param:"+param.toString());
		          out.write(param.toString());
            }
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {            
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result.toString();
    }
}
